package com.tbl.modules.wms2.service.impl.common;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tbl.modules.wms2.common.support.YclCountEntity;
import com.tbl.modules.wms2.dao.common.CountDao;
import com.tbl.modules.wms2.service.common.CountService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 库存
 *
 * @author DASH
 */
@Service
public class CountServiceImpl extends ServiceImpl<CountDao, YclCountEntity> implements CountService {

    @Resource
    CountDao countDao;

    @Override
    public YclCountEntity get(Integer year, Integer month, Integer dayOfMonth, String id) {
        Wrapper ew = new EntityWrapper<YclCountEntity>();
        ew
                .eq("YEAR", year)
                .eq("MONTH", month)
                .eq("DAY", dayOfMonth)
                .eq("ID", id);
        return this.selectOne(ew);
    }

    @Override
    public YclCountEntity getById(String id) {
        return this.selectById(id);
    }

    @Override
    public List<YclCountEntity> getALL() {
        return this.selectList(null);
    }

    @Override
    public Boolean update(YclCountEntity entity) {
        return this.insertOrUpdate(entity);
    }

    @Override
    public String getNextCount(String var) {

        Integer count;

        Date date = DateUtil.date();
        Integer year = DateUtil.year(date);
        Integer month = DateUtil.month(date) + 1;
        Integer dayOfMonth = DateUtil.dayOfMonth(date);
        YclCountEntity yclCountEntity = get(year, month, dayOfMonth, var);
        if (yclCountEntity == null) {
            YclCountEntity entity = getById(var);
            entity.setYear(year);
            entity.setMonth(month);
            entity.setDay(dayOfMonth);
            entity.setCount(2);
            count = 1;
            update(entity);
        } else {
            count = yclCountEntity.getCount();
            yclCountEntity.setCount(count + 1);
            update(yclCountEntity);
        }
        String countStr = count.toString();
        while (countStr.length() < 4) {
            countStr = "0" + countStr;
        }
        String monthStr = month.toString();
        while (monthStr.length() < 2) {
            monthStr = "0" + monthStr;
        }
        String dayOfMonthStr = dayOfMonth.toString();
        while (dayOfMonthStr.length() < 2) {
            dayOfMonthStr = "0" + dayOfMonthStr;
        }
        return var + year.toString() + monthStr + dayOfMonthStr + countStr;
    }

}
